package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.qo.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.util.RequriedPermission;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;

import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@Service
public class PermissionServiceImpl implements IPermissionService{
	@Autowired
	private PermissionMapper permissionMapper;
	@Override
	public void insert(Permission permission) {
		permissionMapper.insert(permission);
	}

	@Override
	public void delete(Long id) {
		permissionMapper.delete(id);
	}

	@Autowired
	private ApplicationContext ctx;


	@Override
	public Permission select(Long id) {
		Permission permission = permissionMapper.select(id);
		return permission;
	}

	@Override
	public List<Permission> list() {
		List<Permission> list = permissionMapper.list();
		return list;
	}

	public PageInfo<Permission> query(QueryObject qo) {
		PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Permission> permissions = permissionMapper.selectForList(qo);
        return new PageInfo<Permission>(permissions);
	}

	public void reload() {
		List<String> expressions = permissionMapper.selectExpressions();

		Map<String, Object> beansMap = ctx.getBeansWithAnnotation(Controller.class);
		Collection<Object> controllerBeans = beansMap.values();
		for (Object controllerBean : controllerBeans) {
			Class<?> controllerBeanClass = controllerBean.getClass().getSuperclass();
			Method[] methods = controllerBeanClass.getDeclaredMethods();
			for (Method method : methods) {
				//获取自定义注解,如果方法没有贴注解返回null
				RequiresPermissions requriesPermissionAnnotations = method.getAnnotation(RequiresPermissions.class);
				//获取自定义注解的name属性值
				if(requriesPermissionAnnotations != null){
					String[] values = requriesPermissionAnnotations.value();
					String name = values[1];
					//String expression = StringUtil.getExpression(method);
					String expression = values[0];
					if(!expressions.contains(expression)){

						Permission permission = new Permission();
						permission.setExpression(expression);
						permission.setName(name);

						permissionMapper.insert(permission);
					}

				}
			}

		}
	}

	public List<String> selectByEmployeeId(Long employeeId) {
		List<String> expressions = permissionMapper.selectByEmployeeId(employeeId);
		return expressions;
	}


}
